<?php
/**
 * @author guoxiaoyong
 */
namespace frontend\controllers;

use bc\controller\FrontController;
use bc\ar\MActiveRecord;
use yii\web\Session;
use bc\model\BabyModel;
use bc\model\baby\ActivityModel;
use bc\model\baby\LogModel;
use bc\model\baby\StatisticModel;
use bc\model\baby\ConfigModel;

class BabyController extends FrontController
{
	
	
	protected $jobs = [
			1 => [
				'val' => 1,
				'job' => '哒哒哒黑猫警长',
				'description' => 'bibibi！不许动！我已经报警了！',
				'img' => 'http://wx.zhishimama.com/baby/img/a_19.jpg'
			],
			2 => [
				'val' => 2,
				'job' => '哗哗哗大作家',
				'description' => '悬梁刺股，奋笔疾书，深藏功与名！',
				'img' => 'http://wx.zhishimama.com/baby/img/a_0.jpg'
			],
			3 => [
				'val' => 3,
				'job' => '特种兵欧巴',
				'description' => '上天遁地我无所畏惧，只是要借助飞机，挖掘机。',
				'img' => 'http://wx.zhishimama.com/baby/img/a_11.jpg'
			],
			4 => [
				'val' => 4,
				'job' => '老戏骨演员',
				'description' => '如果再给我一次机会，我想熟读倒背演员自我修养！',
				'img' => 'http://wx.zhishimama.com/baby/img/a_9.jpg'
			],
			5 => [
				'val' => 5,
				'job' => '蒙面歌手',
				'description' => '立白歌手之我是洗衣粉！',
				'img' => 'http://wx.zhishimama.com/baby/img/a_15.jpg'
			],
			6 => [
				'val' => 6,
				'job' => '灵魂演奏家',
				'description' => '台下一分钟，台上十年功！谁叫我天赋异禀！',
				'img' => 'http://wx.zhishimama.com/baby/img/a_8.jpg'
			],
			7 => [
				'val' => 7,
				'job' => '全能运动员',
				'description' => '运动只是我的业余爱好，其实我是表！情！帝！',
				'img' => 'http://wx.zhishimama.com/baby/img/a_4.jpg'
			],
			8 => [
				'val' => 8,
				'job' => '相声艺术家',
				'description' => '我的天哪！你是传说中的小小小岳岳嘛！',
				'img' => 'http://wx.zhishimama.com/baby/img/a_17.jpg'
			],
			9 => [
				'val' => 9,
				'job' => '小卷毛法官',
				'description' => '我发如雪好像方便面！公正之锤砸呀砸呀砸！',
				'img' => 'http://wx.zhishimama.com/baby/img/a_16.jpg'
			],
			10 => [
				'val' => 10,
				'job' => '奥特曼宇航员',
				'description' => 'Yes Sir，我在火星种土豆！',
				'img' => 'http://wx.zhishimama.com/baby/img/a_6.jpg'
			],
			11 => [
				'val' => 11,
				'job' => '大大大科学家',
				'description' => '哟哟切克闹！我为祖国造大炮！',
				'img' => 'http://wx.zhishimama.com/baby/img/a_13.jpg'
			],
			12 => [
				'val' => 12,
				'job' => '霸道癌CEO',
				'description' => '这片鱼塘我包了！从此升任白富美，迎娶CEO，走向人生巅峰！',
				'img' => 'http://wx.zhishimama.com/baby/img/a_2.jpg'
			],
			13 => [
				'val' => 13,
				'job' => '医生爸爸',
				'description' => '杀！华佗给了你个桃！华佗又给了你个桃！',
				'img' => 'http://wx.zhishimama.com/baby/img/a_7.jpg'
			],
			14 => [
					'val' => 14,
					'job' => '帅帅都叫兽',
					'description' => 'You are my destiny！You are my destiny...',
					'img' => 'http://wx.zhishimama.com/baby/img/a_14.jpg'
			],
			15 => [
					'val' => 15,
					'job' => 'IT程序猿',
					'description' => 'Just do IT.要做就要做IT!听说Nike要干掉我！',
					'img' => 'http://wx.zhishimama.com/baby/img/a_1.jpg'
			],
			16 => [
					'val' => 16,
					'job' => '大长腿模特',
					'description' => '大海啊都是水！我啊只有腿！',
					'img' => 'http://wx.zhishimama.com/baby/img/a_5.jpg'
			],
			17 => [
					'val' => 17,
					'job' => '潇洒诗人',
					'description' => '生活不只是眼前的苟且,还有诗和远方',
					'img' => 'http://wx.zhishimama.com/baby/img/a_12.jpg'
			],
			18 => [
					'val' => 18,
					'job' => '金牌主持人',
					'description' => '有人模仿我的脸，有人模仿我的面，但模仿不了我的...这酸爽~',
					'img' => 'http://wx.zhishimama.com/baby/img/a_3.jpg'
			],
			19 => [
					'val' => 19,
					'job' => '跳跳跳舞蹈家',
					'description' => '完美！',
					'img' => 'http://wx.zhishimama.com/baby/img/a_10.jpg'
			],
			20 => [
					'val' => 20,
					'job' => '加盒饭导演',
					'description' => '我不仅主导自己的人生，还能导导别人de，别动物de，别植物de...',
					'img' => 'http://wx.zhishimama.com/baby/img/a_18.jpg'
			],
			
	];
	
	
	public function init()
	{
		parent::init();
		$session  = new Session();
		
		if(!$session->get('user'))
		{
			$this->setOAuth();
		}
		
		$user = $session->get('user');
		
		if(!$user)
		{
			$this->redirect('/');
		}
		
	}
	
	/**
	 * 首页
	 */
	public function actionIndex()
	{
		$session = new Session();
		$user = $session->get('user');
		
		
		$this->redirect('/baby/top');
		
		$openid = $user['openid'];
		$cookieNickname = $_COOKIE ['baby_nickname'] ? $_COOKIE ['baby_nickname'] : '';
		
		$babyModel = new BabyModel();
		$params['openid'] = $openid;
		$row = $babyModel->getRow($params);
		
		$play = 'enabled';
		$play_count = 3;
		
		$uniqid = uniqid();
		
		$_SESSION['baby_activity'] =$uniqid;
		
		if($row)
		{
			//玩过游戏
			$activityModel = new ActivityModel();
			$activityModel->sort = 'activity_id DESC';
			$activity_params['baby_id'] = $row['id'];
			$activityModel->sort = 'activity_id DESC';
			$activityList = $activityModel->getList($activity_params);
			$activityRow = $activityList[0];
			$redirect_uri = urlencode('http://wx.zhishimama.com/baby/share?activity_id='.$activityRow['activity_id']);
			$view['baby_nickname'] = $row['baby_nickname'];
			$view['title'] = '';
			
			
			$play_count = $row['play_count'] + $row['play_friend_count'];
			if($play_count >0)
			{
				//还能继续玩
				$play = 'enabled';
			}
			else
			{
				//不能在玩了
				$play = 'disabled';
			}
			
			if($play == 'disabled')
			{
				$view['title'] =  '糟了，宝宝没有精力了！Help！Help！';
				$view['content'] = '就差一点点就能拿到迪士尼门票了啊！';
			}
			else
			{
				$view['title'] =  '我的宝宝未来竟然是。。。';
				$view['content'] = '你的宝宝未来到底做什么？天了噜！还不来看看！';
			}
			
		}
		else 
		{
			$redirect_uri = urlencode('http://wx.zhishimama.com/baby/index');
			$view['title'] =  '我的宝宝未来竟然是。。。';
			$view['content'] = '你的宝宝未来到底做什么？天了噜！还不来看看！';
		}
		
		
		//生成js sdk签名
		$jsConfig = $this->configJsApi();
		$appid = $this->wechat()->appid;
		$secret = $this->wechat()->secret;
		$share_url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$appid}&redirect_uri={$redirect_uri}&response_type=code&scope=snsapi_userinfo&#wechat_redirect";
		
		$view['play_count'] = $play_count;
		$view['user'] = $user;
		$view['row'] = $row;
		$view['js_config'] = $jsConfig;
		$view['play'] = $play;
		$view['share_url'] = $share_url;
		$view['uniqid'] = $uniqid;
		return $this->render('index', $view);
	}
	
	/**
	 * 积分结果页
	 */
	public function actionResult()
	{
		$view = [];
		
		$session = new Session();
		$user = $session->get('user');
		$uniqid = $this->get('uniqid');
		
		$babyModel = new BabyModel();
		$activityModel = new ActivityModel();
		
		$row = $babyModel->getRow(['openid' => $user['openid']]);	
		
		$play_count = $row['play_count'] + $row['play_friend_count'];
		
		
		if($_SESSION['baby_activity'] == $uniqid && $play_count > 0)
		{
			
			if($row['play_count'] > 0)
			{
				$babyData['play_count'] = $row['play_count'] - 1;
				$babyModel->modify($babyData, $row['id']);
			}
			else
			{
				if($row['play_friend_count'] >0)
				{
					$babyData['play_friend_count'] = $row['play_friend_count'] - 1;
					$babyModel->modify($babyData, $row['id']);
				}
			}
			
			//获取游戏结果
			$result = $this->getResult();
			
			
			//增加一次游戏记录
			$activityData['baby_id'] = $row['id'];
			$activityData['val_id'] = $result['val'];
			$activityData['nickname'] = $row['baby_nickname'];
			$activityData['create_time'] = time();
			$id = $activityModel->add($activityData);
			$view['activity_id'] = $id;
			
			//宝宝的行业数更新
			$baby_activity_sql = 'select activity_id from bc_baby_activity where baby_id = ' . $row['id'] . ' group by val_id';
			$dao = new MActiveRecord();
			$baby_activity_result = $dao->getDb()->createCommand($baby_activity_sql)->queryAll();
			$count = count($baby_activity_result);
			$play_date = time();
			
			if($row == $count)
			{
				$update_sql = "update bc_baby set job_count = {$count} where id = " . $row['id'];
				$dao->getDb()->createCommand($update_sql)->execute();
			}
			else 
			{
				$update_sql = "update bc_baby set job_count = {$count}, play_date = {$play_date} where id = " . $row['id'];
				$dao->getDb()->createCommand($update_sql)->execute();
			}
			
			
			
		}
		else 
		{
			$activityModel->sort = 'activity_id DESC';
			$lastActivity = $activityModel->getList(['baby_id' => $row['id']]);
			$lastActivity = $lastActivity[0];
			$result = $this->jobs[$lastActivity['val_id']];
			$view['activity_id'] = $lastActivity['activity_id'];
		}
		
		
		//生成js sdk签名
		$jsConfig = $this->configJsApi();
		$appid = $this->wechat()->appid;
		$secret = $this->wechat()->secret;
		$redirect_uri = 'http://wx.zhishimama.com/baby/share?activity_id='.$view['activity_id'];
		$share_url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$appid}&redirect_uri={$redirect_uri}&response_type=code&scope=snsapi_userinfo&#wechat_redirect";
		
		
		//计算排名
		$dao = new MActiveRecord();
		$sql = 'SELECT * FROM bc_baby ORDER BY job_count DESC, play_date ASC';
		$all = $dao->getDb()->createCommand($sql)->queryAll();
		$top = 1;
		
		foreach ($all as $key=>$item)
		{
			if($item['openid'] == $user['openid'])
			{
				$top = $key + 1;//排名是第几位
				break;
			}
		}
		
		
		//销毁session
		$_SESSION['baby_activity'] = '';
		unset($_SESSION['baby_activity']);
		
		$row = $babyModel->getRow(['openid' => $user['openid']]);
		
		$view['title'] =  '我的宝宝未来竟然是。。。';
		$view['content'] = '你的宝宝未来到底做什么？天了噜！还不来看看！';
		
		$view['row'] = $row;
		$view['result'] = $result;
		$view['js_config'] = $jsConfig;
		$view['share_url'] = $share_url;
		$view['top'] = $top;
		return $this->render('result', $view);
		
	}
	
	/**
	 * 分享页
	 */
	public function actionShare()
	{
		$activityId = $this->get('activity_id');
		
		$babyModel = new BabyModel();
		$activityModel = new ActivityModel();
		$activity = $activityModel->getRow(['activity_id' => $activityId]);
		
		if(!$activity)
			$this->redirect('/');
		
		$row = $babyModel->getRow(['id' => $activity['baby_id']]);
		
		$res = $this->jobs[$activity['val_id']];
		
		
		//判断当前用户是否给介绍人加过精力
		$session = new Session();
		$user = $session->get('user');
		$logModel = new LogModel();
		$logParams['baby_id'] = $row['id'];
		$logParams['openid'] = $user['openid'];
		
		$exists = $logModel->getRow($logParams);
		
		
		//计算排名
		$dao = new MActiveRecord();
		$sql = 'SELECT * FROM bc_baby ORDER BY job_count DESC, play_date ASC';
		$all = $dao->getDb()->createCommand($sql)->queryAll();
		$top = 1;
		
		foreach ($all as $key=>$item)
		{
			if($item['openid'] == $row['openid'])
			{
				$top = $key + 1;//排名是第几位
				break;
			}
		}
		
		//生成js sdk签名
		$jsConfig = $this->configJsApi();
		$appid = $this->wechat()->appid;
		$secret = $this->wechat()->secret;
		$redirect_uri = urlencode('http://wx.zhishimama.com/baby/share?activity_id='.$activityId);
		$share_url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$appid}&redirect_uri={$redirect_uri}&response_type=code&scope=snsapi_userinfo&#wechat_redirect";
		
		$view['title'] =  '糟了，宝宝没有精力了！Help！Help！';
		$view['content'] = '就差一点点就能拿到迪士尼门票了啊！';
		$view['js_config'] = $jsConfig;
		$view['share_url'] = $share_url;
		
		
		$view['user'] = $user;
		$view['res'] = $res;
		$view['row'] = $row;
		$view['activity'] = $activity;
		$view['top'] = $top;
		$view['exists'] = $exists;
		return $this->render('share', $view);
		
	}
	
	/**
	 * top排行榜
	 */
	public function actionTop()
	{
		$openId = $this->get('openid', '');
		
		if(!$openId)
		{
			$session = new Session();
			$user = $session->get('user');
			$openId = $user['openid'];
			$babyModel = new BabyModel();
			$row = $babyModel->getRow(['openid' => $user['openid']]);
			$view['row'] = $row;
		}
		
		$dao = new MActiveRecord();
		$sql = 'SELECT * FROM bc_baby ORDER BY job_count DESC, play_date ASC';
		$all = $dao->getDb()->createCommand($sql)->queryAll();
		$self['id'] = 0;
		
		foreach ($all as $key=>$item)
		{
			if($item['openid'] == $openId)
			{
				$self = $item;
				$self['top'] = $key + 1;//排名是第几位
			}
		}
		
		
		//生成js sdk签名
		$jsConfig = $this->configJsApi();
		$appid = $this->wechat()->appid;
		$secret = $this->wechat()->secret;
		$redirect_uri = urlencode('http://wx.zhishimama.com/baby/top?openid='.$openId);
		$share_url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$appid}&redirect_uri={$redirect_uri}&response_type=code&scope=snsapi_userinfo&#wechat_redirect";
		
		$view['title'] =  '我的宝宝竟然上了职业福布斯排行榜！';
		$view['content'] = '天哪！还有迪士尼门票免费拿！';
		$view['js_config'] = $jsConfig;
		$view['all'] = $all;
		$view['self'] = $self;
		$view['share_url'] = $share_url;
		$view['openid'] = $openId;
		return $this->render('top', $view);
		
	}
	
	
	/**
	 * 灵丹妙药页
	 */
	public function actionGift()
	{
		//生成js sdk签名
		$jsConfig = $this->configJsApi();
		$appid = $this->wechat()->appid;
		$secret = $this->wechat()->secret;
		$redirect_uri = 'http://wx.zhishimama.com/baby/gift';
		$share_url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$appid}&redirect_uri={$redirect_uri}&response_type=code&scope=snsapi_userinfo&#wechat_redirect";
		
		
		$configModel = new ConfigModel();
		$row = $configModel->getRowById(1);
		
		
		$view['share_url'] =  $share_url;
		$view['title'] =  '限量版大礼包剩余不多啦！';
		$view['content'] = '礼包已经到手，你们还不赶快来抢！';
		
		$view['js_config'] = $jsConfig;
		
		$view['row'] = $row;
		
		return $this->render('gift', $view);
	}
	
	/**
	 * ajax方式保存昵称到cookie里
	 */
	public function actionAjaxnickname()
	{
		$res['result'] = 0;
		$nickname = $this->post('nickname');
		$session = new Session();
		$user = $session->get('user');
		if($nickname)
		{
			setcookie('baby_nickname', $nickname, time()+60*60*24*30);
			$res['result'] = 1;
			
			$babyModel = new BabyModel();
			
			$row = $babyModel->getRow(['openid' => $user['openid']]);
			if(!$row)
			{
				$babyData['baby_nickname'] = $nickname;
				$babyData['openid'] = $user['openid'];
				$babyData['play_count'] = 3;
				$babyData['play_date'] = strtotime(date('Y-m-d'));
				$babyData['play_friend_count'] = 0;
				$babyData['job_count'] = 0;
				$babyData['create_time'] = time();
				$babyModel->add($babyData);
			}
			
			
		}
		echo json_encode($res);
		exit;
	}
	
	
	/**
	 * Ajax获取结果
	 */
	public function actionAjaxresult()
	{
		
	}
	
	//ajax分享统计
	public function actionStatistic()
	{
		$pageId = $this->post('page_id');
		$url = $this->post('url');
		$activityId = $this->post('activity_id');
		
		$statisticModel = new StatisticModel();
		$data['page_id'] = $pageId;
		$data['url'] = $url;
		$data['create_time'] = time();
		$statisticModel->add($data);
		
		if($pageId == 2 && $activityId)
		{
			//统计每个用户对结果显示的统计
			
			$activityModel = new ActivityModel();
			$row = $activityModel->getRow(['activity_id' => $activityId]);
			$activityData['share_count'] = $row['share_count'] + 1;
			$activityModel->modify($activityData, $activityId);
			
		}
		
	}
	
	
	
	public function actionTest()
	{
		$session = new Session();
		$user = $session->get('user');
	
		$openid = $user['openid'];
		$cookieNickname = $_COOKIE ['baby_nickname'] ? $_COOKIE ['baby_nickname'] : '';
	
		$babyModel = new BabyModel();
		$params['openid'] = $openid;
		$row = $babyModel->getRow($params);
	
		$play = 'enabled';
		$play_count = 3;
	
		$uniqid = uniqid();
	
		$_SESSION['baby_activity'] =$uniqid;
	
		if($row)
		{
			//玩过游戏
			$activityModel = new ActivityModel();
			$activityModel->sort = 'activity_id DESC';
			$activity_params['baby_id'] = $row['id'];
			$activityModel->sort = 'activity_id DESC';
			$activityList = $activityModel->getList($activity_params);
			$activityRow = $activityList[0];
			$redirect_uri = urlencode('http://wx.zhishimama.com/baby/share?activity_id='.$activityRow['activity_id']);
			$view['baby_nickname'] = $row['baby_nickname'];
			$view['title'] = '';
				
				
			$play_count = $row['play_count'] + $row['play_friend_count'];
			if($play_count >0)
			{
				//还能继续玩
				$play = 'enabled';
			}
			else
			{
				//不能在玩了
				$play = 'disabled';
			}
				
			if($play == 'disabled')
			{
				$view['title'] =  '糟了，宝宝没有精力了！Help！Help！';
				$view['content'] = '就差一点点就能拿到迪士尼门票了啊！';
			}
			else
			{
				$view['title'] =  '我的宝宝未来竟然是。。。';
				$view['content'] = '你的宝宝未来到底做什么？天了噜！还不来看看！';
			}
				
		}
		else
		{
			$redirect_uri = urlencode('http://wx.zhishimama.com/baby/index');
			$view['title'] =  '我的宝宝未来竟然是。。。';
			$view['content'] = '你的宝宝未来到底做什么？天了噜！还不来看看！';
		}
	
	
		//生成js sdk签名
		$jsConfig = $this->configJsApi();
		$appid = $this->wechat()->appid;
		$secret = $this->wechat()->secret;
		$share_url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$appid}&redirect_uri={$redirect_uri}&response_type=code&scope=snsapi_userinfo&#wechat_redirect";
	
		$view['play_count'] = $play_count;
		$view['user'] = $user;
		$view['row'] = $row;
		$view['js_config'] = $jsConfig;
		$view['play'] = $play;
		$view['share_url'] = $share_url;
		$view['uniqid'] = $uniqid;
		return $this->render('index', $view);
	}
	
	/**
	 * Ajax给用户点赞
	 */
	public function actionAjaxsupport()
	{
		$msg['result'] = 0;
		
		$logModel = new LogModel();
		
		$babyId = $this->post('baby_id');
		
		$session = new Session();
		$user = $session->get('user');
		
		$params['baby_id'] = $babyId;
		$params['openid'] = $user['openid'];
		$row = $logModel->getRow($params);
		if(!$row)
		{
			//给用户点赞
			$babyModel = new BabyModel();
			$babyRow = $babyModel->getRowById($babyId);
			$babyData['play_friend_count'] = $babyRow['play_friend_count'] + 1;
			$babyModel->modify($babyData, $babyId);
			
			$logData['baby_id'] = $babyId;
			$logData['openid'] = $user['openid'];
			$logData['create_time'] = time();
			$logModel->add($logData);
			$msg['result'] = 1;			
		}
		
		echo json_encode($msg);
		exit;
		
	}
	
	
	private function getResult()
	{
		$rand = rand(1, 1000);
		
		$result = [];
		
		if($rand <= 50 )
		{
			$result = $this->jobs[1];
		}
		elseif($rand > 50 && $rand <= 80)
		{
			$result = $this->jobs[2];
		}
		elseif($rand > 80 && $rand <= 130)
		{
			$result = $this->jobs[3];
		}
		elseif($rand > 130 && $rand <= 160)
		{
			$result = $this->jobs[4];
		}
		elseif($rand > 160 && $rand <= 190)
		{
			$result = $this->jobs[5];
		}
		elseif($rand > 190 && $rand <= 200)
		{
			$result = $this->jobs[6];
		}
		elseif($rand > 200 && $rand <= 300)
		{
			$result = $this->jobs[7];
		}
		elseif($rand > 300 && $rand <= 350)
		{
			$result = $this->jobs[8];
		}
		elseif($rand > 350 && $rand <= 370)
		{
			$result = $this->jobs[9];
		}
		elseif($rand > 370 && $rand <= 390)
		{
			$result = $this->jobs[10];
		}
		elseif($rand > 390 && $rand <= 440)
		{
			$result = $this->jobs[11];
		}
		elseif($rand > 440 && $rand <= 490)
		{
			$result = $this->jobs[12];
		}
		elseif($rand > 490 && $rand <= 540)
		{
			$result = $this->jobs[13];
		}
		elseif($rand > 540 && $rand <= 590)
		{
			$result = $this->jobs[14];
		}
		elseif($rand > 590 && $rand <= 690)
		{
			$result = $this->jobs[15];
		}
		elseif($rand > 690 && $rand <= 790)
		{
			$result = $this->jobs[16];
		}
		elseif($rand > 790 && $rand <= 840)
		{
			$result = $this->jobs[17];
		}
		elseif($rand > 840 && $rand <= 940)
		{
			$result = $this->jobs[18];
		}
		elseif($rand > 940 && $rand <= 970)
		{
			$result = $this->jobs[19];
		}
		else 
		{
			$result = $this->jobs[20];
		}
		return $result;
	}
}

